<script setup>
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';
import defaultAvatar from '@/assets/default.png';

const userStore = useUserStore();
const avatarUrl = ref('');
const file = ref(null);

// 初始化头像：优先从本地存储获取，其次从Pinia，最后用默认头像
onMounted(() => {
  // 1. 先从localStorage读取
  const localAvatar = localStorage.getItem('userAvatar');
  if (localAvatar) {
    avatarUrl.value = localAvatar;
    // 同步更新到Pinia（避免状态不一致）
    userStore.setUser({
      ...userStore.user,
      userPic: localAvatar
    });
  } else {
    // 2. 再从Pinia获取
    avatarUrl.value = userStore.user.userPic || defaultAvatar;
  }
});

// 处理文件选择
const handleFileChange = (e) => {
  const selectedFile = e.target.files[0];
  if (selectedFile) {
    file.value = selectedFile;
    // 预览头像
    const reader = new FileReader();
    reader.onload = (event) => {
      avatarUrl.value = event.target.result;
    };
    reader.readAsDataURL(selectedFile);
  }
};

// 保存头像：同步更新到本地存储和Pinia
const saveAvatar = () => {
  if (!file.value) {
    ElMessage.warning('请选择图片文件');
    return;
  }

  // 1. 保存到localStorage（核心：实现本地存储）
  localStorage.setItem('userAvatar', avatarUrl.value);
  
  // 2. 同步更新到Pinia状态
  userStore.setUser({
    ...userStore.user,
    userPic: avatarUrl.value
  });
  
  ElMessage.success('头像更新成功');
};
</script>

<template>
  <!-- 模板内容不变 -->
  <div class="avatar-container">
    <el-card>
      <div slot="header">
        <h2>更换头像</h2>
      </div>
      
      <div class="avatar-uploader">
        <div class="avatar-preview">
          <el-avatar :size="150" :src="avatarUrl">
            <img :src="avatarUrl" alt="用户头像">
          </el-avatar>
        </div>
        
        <div class="upload-area">
          <el-button type="primary" @click="$refs.fileInput.click()">选择图片</el-button>
          <input 
            ref="fileInput" 
            type="file" 
            accept="image/*" 
            @change="handleFileChange"
            class="hidden-input"
          >
          <p class="tip">支持JPG、PNG格式，建议尺寸200x200px</p>
        </div>
        
        <div class="action-buttons">
          <el-button type="primary" @click="saveAvatar">保存头像</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
/* 样式不变 */
.avatar-container {
  padding: 20px;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 0;

  .avatar-preview {
    margin-bottom: 30px;
  }

  .upload-area {
    text-align: center;
    margin-bottom: 20px;

    .hidden-input {
      display: none;
    }

    .tip {
      margin-top: 10px;
      color: #666;
      font-size: 12px;
    }
  }
}
</style>